<template>
  <div class="user-center-container">
    <el-card class="user-info-card" shadow="hover">
      <div slot="header" class="card-header">
        <h2 class="card-title">个人中心</h2>
      </div>

      <div class="user-info-wrapper">
        <!-- 头像展示 -->
        <div class="user-avatar">
          <img
            :src="getAvatarUrl(userInfo.avatar)"
            alt="用户头像"
            class="avatar-image"
          />
          <div class="avatar-status-dot" :class="{ online: true }"></div>
        </div>

        <!-- 信息列表 -->
        <el-descriptions :column="1" border class="info-descriptions">
          <el-descriptions-item label="姓名" class="info-item">{{
            userInfo.name || "未设置"
          }}</el-descriptions-item>
          <el-descriptions-item label="出生日期" class="info-item">{{
            formatDate(userInfo.birthDate) || "未设置"
          }}</el-descriptions-item>
          <el-descriptions-item label="性别" class="info-item">{{
            getUserGender(userInfo.gender) || "未设置"
          }}</el-descriptions-item>
          <el-descriptions-item label="所在地" class="info-item">{{
            userInfo.location || "未设置"
          }}</el-descriptions-item>
        </el-descriptions>
        <el-button
          type="primary"
          size="small"
          @click="openEditDialog"
          class="edit-btn"
        >
          <i class="el-icon-edit mr-1"></i>修改信息
        </el-button>
      </div>
    </el-card>

    <!-- 修改信息弹窗 -->
    <el-dialog
      title="修改个人信息"
      :visible.sync="editDialogVisible"
      width="35%"
      center
    >
      <el-form
        :model="editForm"
        :rules="rules"
        ref="editFormRef"
        label-width="100px"
        class="edit-form"
      >
        <el-form-item label="头像">
          <div class="avatar-upload-wrapper">
            <div class="avatar-uploader" @click="triggerUpload">
              <img
                v-if="editForm.avatar"
                :src="getAvatarUrl(editForm.avatar)"
                class="avatar-edit-image"
              />
              <div v-else class="avatar-placeholder">
                <i class="el-icon-plus"></i>
                <p>点击上传</p>
              </div>
            </div>
            <p class="avatar-tip">支持 JPG、PNG 格式，不超过 2MB</p>
          </div>
          <el-upload
            ref="uploadRef"
            :auto-action="false"
            :show-file-list="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            style="display: none"
          />
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="editForm.name"
            placeholder="请输入姓名"
            class="input-width"
          />
        </el-form-item>

        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker
            type="date"
            placeholder="选择出生日期"
            v-model="editForm.birthDate"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            class="input-width"
          />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editForm.gender" class="gender-radio">
            <el-radio :label="'男'">男</el-radio>
            <el-radio :label="'女'">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="所在地" prop="location" required>
          <localSelect
            v-model="editForm.location"
            :city="editForm.location"
          ></localSelect>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="isSubmitting" @click="handleSave"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { editBasicMessage, uploadAvatar } from "@/api/recuriter/company";
import { Message } from "element-ui";
import localSelect from "@/components/localSelect.vue";
import { getRectuiterBasicInfo } from "../../../api/login";
export default {
  components: { localSelect },
  data() {
    return {
      editDialogVisible: false,
      editForm: {
        name: "",
        birthDate: "",
        gender: "",
        location: "",
        avatar: "", // 存储头像URL
      },
      isSubmitting: false,
      uploadAction: "https://jsonplaceholder.typicode.com/posts/", // 请替换为实际上传接口
      avatarFile: null,
      tempAvatarUrl: null,
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.recruiter.userInfo;
    },
    rules() {
      return {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        birthDate: [
          { required: true, message: "请选择出生日期", trigger: "change" },
        ],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        location: [
          { required: true, message: "请选择所在地", trigger: "change" },
        ],
      };
    },
  },
  methods: {
    getAvatarUrl(avatar) {
      if (!avatar) return "";

      if (avatar.startsWith("data:")) {
        return avatar;
      }
      if (avatar.startsWith("http")) {
        const separator = avatar.includes("?") ? "&" : "?";
        return `${avatar}${separator}t=${Date.now()}`;
      }
      return avatar;
    },
    async reloadUserInfo() {
      try {
        const res = await getRectuiterBasicInfo();
        if (res.data.code === 201) {
          this.$store.commit("recruiter/SET_USER_INFO", res.data.data);
        }
      } catch (error) {
        console.error("重新加载用户信息失败：", error);
      }
    },
    formatDate(dateStr) {
      if (!dateStr) return "";
      return new Date(dateStr).toISOString().split("T")[0];
    },
    getUserGender(gender) {
      return gender === "男" ? "男" : gender === "女" ? "女" : "";
    },
    openEditDialog() {
      this.editForm = {
        name: this.userInfo.name || "",
        birthDate: this.userInfo.birthDate
          ? new Date(this.userInfo.birthDate).toISOString().split("T")[0]
          : "",
        gender: this.getUserGender(this.userInfo.gender) || "男",
        location: this.userInfo.location || "",
        avatar: this.userInfo.avatar || "",
      };
      this.avatarFile = null;
      this.tempAvatarUrl = this.userInfo.avatar || "";
      this.editDialogVisible = true;
    },

    handleDialogClose() {
      this.$refs.editFormRef?.resetFields();
      this.avatarFile = null;
      this.tempAvatarUrl = "";
      this.editDialogVisible = false;
    },

    // 触发文件选择
    triggerUpload() {
      const uploadRef = this.$refs.uploadRef;
      if (uploadRef) {
        uploadRef.$el.querySelector('input[type="file"]').click();
      } else {
        console.error("上传组件引用未找到");
        Message.error("上传组件加载失败，请刷新页面");
      }
    },

    // 上传前验证
    beforeUpload(file) {
      const isImage = file.type.startsWith("image/");
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        Message.error("请上传图片文件");
        return false;
      }
      if (!isLt2M) {
        Message.error("图片大小不能超过2MB");
        return false;
      }
      this.avatarFile = file;
      return true;
    },

    handleFileChange(file) {
      this.avatarFile = file.raw || file; // 确保获取原始文件对象

      // 生成预览URL
      const reader = new FileReader();
      reader.readAsDataURL(this.avatarFile);
      reader.onload = (e) => {
        this.tempAvatarUrl = e.target.result;
        this.editForm.avatar = this.tempAvatarUrl; // 更新预览
      };
    },

    async handleSave() {
      try {
        this.isSubmitting = true;

        // 表单验证
        await new Promise((resolve, reject) => {
          this.$refs.editFormRef.validate((valid) => {
            if (!valid) {
              return;
            }
            resolve();
          });
        });

        // 构造基本信息对象
        const basicData = {
          name: this.editForm.name,
          birthDate: this.formatDateToISO(this.editForm.birthDate),
          gender: this.editForm.gender,
          location: this.editForm.location,
        };

        // 上传头像（如果有选择）
        if (this.avatarFile) {
          const avatarRes = await uploadAvatar(this.avatarFile);
          if (avatarRes.data.code === 201) {
            basicData.avatar = avatarRes.data.url;
            this.$store.commit("recruiter/SET_TOKEN", avatarRes.data.data);
          } else {
            throw new Error("头像上传失败");
          }
        } else if (
          this.editForm.avatar &&
          this.editForm.avatar !== this.userInfo.avatar
        ) {
          basicData.avatar = "";
        }

        // 保存基本信息
        const basicRes = await editBasicMessage(basicData);
        if (basicRes.data.code === 201) {
          // 更新本地状态
          this.$store.commit("recruiter/SET_TOKEN", basicRes.data.data);
          await this.reloadUserInfo();
          this.editDialogVisible = false;

          Message.success("信息修改成功");
        } else {
          throw new Error("信息修改失败");
        }
      } catch (error) {
        console.error("操作失败", error);
        Message.error(error.message || "信息修改失败，请稍后重试");
      } finally {
        this.isSubmitting = false;
      }
    },

    formatDateToISO(dateStr) {
      if (!dateStr) return "";
      const date = new Date(dateStr);
      return date.toISOString();
    },
  },
};
</script>
<style scoped>
/* 样式保持不变，沿用之前优化的样式 */
.user-center-container {
  padding: 30px 10px;
  min-height: 100vh;
}

.user-info-card {
  max-width: 600px;
  margin: 0 auto;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  border-radius: 12px;
  transition: all 0.3s ease;
}

.card-header {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.card-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.edit-btn {
  height: 32px;
  padding: 0 16px;
  font-size: 14px;
  transition: all 0.2s;
  margin-top: 20px;
}

.edit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.3);
}

.user-info-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px 0;
}

.user-avatar {
  position: relative;
  margin-bottom: 30px;
}

.avatar-image {
  width: 140px;
  height: 140px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #fff;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.avatar-image:hover {
  transform: scale(1.03);
  box-shadow: 0 6px 30px rgba(64, 158, 255, 0.25);
}

.avatar-status-dot {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background-color: #67c23a;
  border: 2px solid #fff;
  box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.3);
}

.online {
  animation: pulse 2s infinite;
}

.info-descriptions {
  width: 100%;
  max-width: 400px;
}

.info-item {
  font-size: 16px;
  color: #606266;
}

.el-descriptions__item {
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;
}

.el-descriptions__item:last-child {
  border-bottom: none;
}

.el-descriptions__label {
  font-weight: 500;
  color: #909399;
}

/* 编辑弹窗样式 */
.edit-dialog {
  border-radius: 10px;
}

.edit-form {
  width: 100%;
}

.avatar-upload-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-uploader {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  border: 2px dashed #dcdfe6;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s;
  margin-bottom: 10px;
}

.avatar-uploader:hover {
  border-color: #409eff;
  transform: scale(1.02);
}

.avatar-edit-image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.avatar-placeholder i {
  font-size: 28px;
  color: #909399;
  margin-bottom: 10px;
}

.avatar-placeholder p {
  font-size: 14px;
  color: #909399;
}

.avatar-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.input-width {
  width: 100%;
}

.gender-radio {
  display: flex;
  gap: 20px;
}

.el-radio__label {
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 15px;
  padding: 20px 0;
}

/* 动画 */
@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(103, 194, 58, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-center-container {
    padding: 20px 15px;
  }

  .user-info-card {
    max-width: 100%;
  }

  .card-header {
    padding: 20px 0;
  }

  .card-title {
    font-size: 20px;
  }

  .edit-dialog {
    width: 90%;
  }
}
</style>